package com.daiyang.lottery.service.impl;

import com.daiyang.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.daiyang.lottery.common.exception.ServiceException;
import com.daiyang.lottery.common.util.JacksonUtil;
import com.daiyang.lottery.common.util.RedisUtil;
import com.daiyang.lottery.controller.param.CreateActivityParam;
import com.daiyang.lottery.controller.param.CreatePrizeByActivityParam;
import com.daiyang.lottery.controller.param.CreateUserByActivityParam;
import com.daiyang.lottery.controller.param.PageListParam;
import com.daiyang.lottery.dao.dataobject.ActivityDO;
import com.daiyang.lottery.dao.dataobject.ActivityPrizeDO;
import com.daiyang.lottery.dao.dataobject.ActivityUserDO;
import com.daiyang.lottery.dao.dataobject.PrizeDO;
import com.daiyang.lottery.dao.mapper.*;
import com.daiyang.lottery.service.ActivityService;
import com.daiyang.lottery.service.UserService;
import com.daiyang.lottery.service.dto.ActivityDTO;
import com.daiyang.lottery.service.dto.ActivityDetailDTO;
import com.daiyang.lottery.service.dto.CreateActivityDTO;
import com.daiyang.lottery.service.dto.PageListDTO;
import com.daiyang.lottery.service.enums.ActivityPrizeStatusEnum;
import com.daiyang.lottery.service.enums.ActivityPrizeTiersEnum;
import com.daiyang.lottery.service.enums.ActivityStatusEnum;
import com.daiyang.lottery.service.enums.ActivityUserStatusEnum;
import jakarta.annotation.Resource;
import org.apache.ibatis.annotations.Options;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl implements ActivityService {


    private static final Logger logger
            = LoggerFactory.getLogger(ActivityServiceImpl.class);
    /**
     * 活动缓存前置，为了区分业务
     */
    private final String ACTIVITY_PREFIX = "ACTIVITY_";
    /**
     * 活动缓存过期时间
     */
    private final Long ACTIVITY_TIMEOUT = 60 * 60 * 24 * 3L;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PrizeMapper prizeMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;
    @Autowired
    private ActivityUserMapper activityUserMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CreateActivityDTO createActivity(CreateActivityParam request) {
        // 校验活动信息是否正确
        checkActivityInfo(request);

        //创建活动
        ActivityDO activityDO = new ActivityDO();
        activityDO.setActivityName(request.getActivityName());
        activityDO.setDescription(request.getDescription());
        activityDO.setStatus(ActivityStatusEnum.RUNNING.name());
        activityMapper.insert(activityDO);

        // 关联活动商品
        List<CreatePrizeByActivityParam> prizeParamList = request.getActivityPrizeList();
        List<ActivityPrizeDO> activityPrizeDOList = new ArrayList<>();
        prizeParamList.forEach(param ->{
            ActivityPrizeDO activityPrizeDO = new ActivityPrizeDO();
            activityPrizeDO.setActivityId(activityDO.getId());
            activityPrizeDO.setPrizeAmount(param.getPrizeAmount());
            activityPrizeDO.setPrizeId(param.getPrizeId());
            activityPrizeDO.setPrizeTiers(param.getPrizeTiers().name());
            activityPrizeDO.setStatus(ActivityPrizeStatusEnum.INIT.name());
            activityPrizeDOList.add(activityPrizeDO);
        });
        System.out.println(JacksonUtil.writeValueAsString(activityPrizeDOList));
        activityPrizeMapper.batchInsert(activityPrizeDOList);

        //关联活动人员

        List<CreateUserByActivityParam> userParamList = request.getActivityUserList();
        List<ActivityUserDO> activityUserDOList =new ArrayList<>();
        userParamList.forEach(param ->{
            ActivityUserDO activityUserDO = new ActivityUserDO();
            activityUserDO.setActivityId(activityDO.getId());
            activityUserDO.setUserId(param.getUserId());
            activityUserDO.setUserName(param.getUserName());
            activityUserDO.setStatus(ActivityUserStatusEnum.INIT.name());
            activityUserDOList.add(activityUserDO);
        });
        System.out.println(JacksonUtil.writeValueAsString(activityUserDOList));
        activityUserMapper.batchInsert(activityUserDOList);

        // 将活动以及关联的奖品缓存到redis
        //查询奖品信息列表
        // activitty: ActivityDetailDTO：活动+奖品+人员
        // 先获取奖品基本属性列表
        // 获取需要找寻的奖品id
        List<Long> prizeidS =activityPrizeDOList.stream()
                .map(ActivityPrizeDO::getPrizeId)
                .distinct()
                .collect(Collectors.toList());
        List<PrizeDO> prizeDOList =prizeMapper.selectByIdList(prizeidS);
        ActivityDetailDTO detailDTO = convertToActivityDetailDTO(activityDO, activityPrizeDOList,
                prizeDOList,activityUserDOList);
        cacheActivity(detailDTO);


        //构建返回
        CreateActivityDTO createActivityDTO = new CreateActivityDTO();
        createActivityDTO.setActivityId(activityDO.getId());
        return createActivityDTO;


    }

    @Override
    public PageListDTO<ActivityDTO> findActivityList(PageListParam request) {
        int count =activityMapper.count();

        List<ActivityDO> activities  =
                activityMapper.queryActivitiesByPage(request.offset(),request.getPageSize());
        List<ActivityDTO> records =new ArrayList<>();
        for (ActivityDO activityDO : activities) {
            ActivityDTO activityDTO=new ActivityDTO();
            activityDTO.setActivityId(activityDO.getId());
            activityDTO.setActivityName(activityDO.getActivityName());
            activityDTO.setDescription(activityDO.getDescription());
            activityDTO.setStatus(
                    ActivityStatusEnum.
                            formName(activityDO.getStatus()));
            records.add(activityDTO);
        }
        return new PageListDTO<>(count,records);
    }

    @Override
    public ActivityDetailDTO getActivityDetail(Long activityId) {
        if(null==activityId){
            logger.warn("查询活动详细信息失败，activityId为空");
        }
        //从redis缓存中获取
        ActivityDetailDTO activityDetailDTO = getActivityFromCache(activityId);
        if(null!=activityDetailDTO){
            logger.info("从redis缓存中获取活动信息成功：{}",
                    JacksonUtil.writeValueAsString(activityDetailDTO));
            return activityDetailDTO;
        }

        //如果redis不存在，查表

        //活动表

        ActivityDO activityDO = activityMapper.selectById(activityId);
        logger.info("从数据库中获取活动信息成功：{}",
                JacksonUtil.writeValueAsString(activityDO));

        //活动奖品表

        List<ActivityPrizeDO> apDOList = activityPrizeMapper.selectByActivityId(activityId);
        logger.info("从数据库中获取活动奖品信息成功：{}",
                JacksonUtil.writeValueAsString(apDOList));

        //活动人员表

        List<ActivityUserDO> auDOList = activityUserMapper.selectByActivityId(activityId);
        logger.info("从数据库中获取活动人员信息成功：{}",
                JacksonUtil.writeValueAsString(auDOList));


        // 奖品表：先获取要查询的奖品id

        List<Long> prizeids=apDOList.stream()
                .map(ActivityPrizeDO::getPrizeId)
               .collect(Collectors.toList());
        List<PrizeDO> pDOList =prizeMapper.selectByIdList(prizeids);


        //整合活动详细信息，存放redis
        activityDetailDTO = convertToActivityDetailDTO(activityDO,apDOList,pDOList,auDOList);

        return activityDetailDTO;


    }

    @Override
    public void cacheActivity(Long activityId) {
        if(activityId==null) {
            logger.warn("缓存活动信息失败，activityId为空");
            throw new ServiceException(ServiceErrorCodeConstants.CACHE_ACTIVITY_ID_IS_EMPTY);
        }

        // 查询表数据：活动表、关联奖品、关联人员、奖品信息表
        ActivityDO aDO = activityMapper.selectById(activityId);
        if(null==aDO) {
            logger.warn("缓存活动信息失败，活动不存在，activityId={}",activityId);
            throw new ServiceException(ServiceErrorCodeConstants.CACHE_ACTIVITY_ID_ERROR);
        }
        // 活动奖品表
        List<ActivityPrizeDO> apDOList =  activityPrizeMapper.selectByActivityId(activityId);
        // 活动人员表
        List<ActivityUserDO> auDOList = activityUserMapper.selectByActivityId(activityId);
        // 奖品表: 先获取要查询的奖品id
        List<Long> prizeIds = apDOList.stream()
                .map(ActivityPrizeDO::getPrizeId)
                .collect(Collectors.toList());
        List<PrizeDO> pDOList = prizeMapper.batchSelectByIds(prizeIds);
        // 整合活动详细信息，存放redis
        cacheActivity(
                convertToActivityDetailDTO(aDO, apDOList,
                        pDOList,auDOList ));
    }


    private void cacheActivity(ActivityDetailDTO detailDTO) {
        //key: ACTIVITY_12
        //value:ActivityDetailDTO(json)

        if(null==detailDTO || null ==detailDTO.getActivityId()){
            logger.warn("要缓存的信息不存在！");
            return;
        }
        try {
            redisUtil.set(ACTIVITY_PREFIX+detailDTO.getActivityId(),
                    JacksonUtil.writeValueAsString(detailDTO),
                    ACTIVITY_TIMEOUT);
        } catch (Exception e) {
            logger.error("缓存活动信息失败！,ActivityDetailDTO:{}"
                    ,JacksonUtil.writeValueAsString(detailDTO),
                    e);
        }

    }
    private ActivityDetailDTO getActivityFromCache(Long activityId) {
        if(null==activityId){
            logger.warn("获取缓存活动数据activityId为空");
            return null;
        }
        try {
            String str = redisUtil.get(ACTIVITY_PREFIX+activityId);
            if(!StringUtils.hasText(str)) {
                logger.info("获取的缓存活动数据为空！ key ={}",ACTIVITY_PREFIX+activityId);
                return null;
            }
            return JacksonUtil.readValue(str, ActivityDetailDTO.class);
        } catch (Exception e) {
            logger.error("从缓存中获取活动信息异常，key={}", ACTIVITY_PREFIX + activityId, e);
            return null;
        }

    }

    private ActivityDetailDTO convertToActivityDetailDTO(ActivityDO activityDO,
                                                        List<ActivityPrizeDO> activityPrizeDOList,
                                                        List<PrizeDO> prizeDOList,
                                                        List<ActivityUserDO> activityUserDOList) {
        ActivityDetailDTO detailDTO = new ActivityDetailDTO();
        detailDTO.setActivityId(activityDO.getId());
        detailDTO.setActivityName(activityDO.getActivityName());
        detailDTO.setDesc(activityDO.getDescription());
        detailDTO.setStatus(ActivityStatusEnum.formName(activityDO.getStatus()));
        // apDO: {prizeId，amount, status}, {prizeId，amount, status}
        // pDO: {prizeid, name....},{prizeid, name....},{prizeid, name....}


        List<ActivityDetailDTO.PrizeDTO> prizeDTOList =activityPrizeDOList
                .stream()
                .map(apDO -> {
                    ActivityDetailDTO.PrizeDTO prizeDTO = new ActivityDetailDTO.PrizeDTO();
                    prizeDTO.setPrizeid(apDO.getPrizeId());
                    Optional<PrizeDO> optionalPrizeDO = prizeDOList.stream()
                            .filter(prizeDO -> prizeDO.getId().equals(apDO.getPrizeId()))
                            .findFirst();
                    // 如果PrizeDO为空，不执行当前方法，不为空才执行
                    optionalPrizeDO.ifPresent(prizeDO -> {
                        prizeDTO.setName(prizeDO.getName());
                        prizeDTO.setImageUrl(prizeDO.getImageUrl());
                        prizeDTO.setPrice(prizeDO.getPrice());
                        prizeDTO.setDescription(prizeDO.getDescription());
                    });
                    prizeDTO.setTiers(ActivityPrizeTiersEnum.formName(apDO.getPrizeTiers()));
                    prizeDTO.setPrizeAmount(apDO.getPrizeAmount());
                    prizeDTO.setStatus(ActivityPrizeStatusEnum.forName(apDO.getStatus()));
                    return prizeDTO;
                }).collect(Collectors.toList());
        detailDTO.setPrizeDTOList(prizeDTOList);


        List<ActivityDetailDTO.UserDTO> userDTOList =activityUserDOList
               .stream()
                .map(auDO -> {
                   ActivityDetailDTO.UserDTO userDTO = new ActivityDetailDTO.UserDTO();
                   userDTO.setUserId(auDO.getUserId());
                   userDTO.setUserName(auDO.getUserName());
                   userDTO.setStatus(ActivityUserStatusEnum.forName(auDO.getStatus()));
                   return userDTO;
               }).collect(Collectors.toList());
        detailDTO.setUserDTOList(userDTOList);
        return detailDTO;
    }

    private void checkActivityInfo(CreateActivityParam param) {
        if(null==param) {
            throw new ServiceException(ServiceErrorCodeConstants.CREATE_ACTIVITY_INFO_IS_EMPTY);
        }
        //人员id在人员表中是否存在
        //1  2  3-》 1  2
        List<Long> userIds = param.getActivityUserList()
                .stream()
                .map(CreateUserByActivityParam::getUserId)
                .distinct()
                .collect(Collectors.toList());
        List<Long> existUserIds = userMapper.selectExistByIds(userIds);

        if(CollectionUtils.isEmpty(existUserIds)) {
            throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_USER_ERROR);
        }
        userIds.forEach(id -> {
            if(!existUserIds.contains(id)) {
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_USER_ERROR);
            }
        });

        // 奖品id在奖品表中是否存在
        List<Long> prizeIds = param.getActivityPrizeList()
                .stream()
                .map(CreatePrizeByActivityParam::getPrizeId)
                .distinct()
                .collect(Collectors.toList());
        List<Long> userIdList = prizeMapper.selectExistByIds(prizeIds);
        if(CollectionUtils.isEmpty(userIdList)) {
            throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_ERROR);
        }
        prizeIds.forEach(id -> {
            if(!userIdList.contains(id)) {
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_ERROR);
            }
        });

        //人员数量大于等于奖品数量

        //2哥奖品 2 1

        int userAmount = param.getActivityUserList().size();
        Long prizeAmount = param.getActivityPrizeList()
                .stream()
                .mapToLong(CreatePrizeByActivityParam::getPrizeAmount)
                .sum();
        if(userAmount<prizeAmount) {
            throw new ServiceException(ServiceErrorCodeConstants.USER_PRIZE_AMOUNT_ERROR);
        }
        //检验活动奖品等级有效性
        param.getActivityPrizeList().forEach(prize -> {
            if (null== ActivityPrizeTiersEnum.formName(prize.getPrizeTiers().name())) {
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_TIERS_ERROR);
            }
        });

    }

}
